package com.autotest.nore.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.alibaba.fastjson2.JSONObject;
import org.apache.hc.client5.http.classic.methods.*;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hc.core5.http.ContentType;
import java.util.*;
import java.util.stream.Collectors;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.StringBody;

import java.io.File;

public class HttpclientUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpclientUtils.class);

    private static CloseableHttpClient httpClient;
    private static CloseableHttpResponse response = null;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(50); // 注意：这里只设置了一次
        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }

    private static Map<String, String> responseHeaders;

    public static void setResponseHeaders(Map<String, String> headers) {
        responseHeaders = headers;
    }

    public static Map<String, String> getResponseHeaders() {
        return responseHeaders;
    }

    /**
     * 普通get请求
     */
    public static String httpCommonGet(String url, Map<String, String> requestHeaders) {
        HttpGet httpGet = new HttpGet(url);

        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpGet.addHeader(entry.getKey(), entry.getValue());
        }

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) { // 使用 getCode() 方法获取状态码
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 普通post请求
     */
    public static String httpCommonPost(String url, Map<String, String> requestHeaders,
                                        Map<String, Object> requestParams) {
        HttpPost httpPost = new HttpPost(url);
        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        // 构建表单数据
        if (requestParams != null) {
            List<NameValuePair> params = new ArrayList<>();
            for (Map.Entry<String, Object> entry : requestParams.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();

                try {
                    if (value instanceof File) {
                        // 如果是文件类型，跳过（不支持文件上传）
                        logger.warn("文件类型不支持 application/x-www-form-urlencoded: key={}", key);
                        continue;
                    } else if (value instanceof String) {
                        // 如果是字符串类型
                        params.add(new BasicNameValuePair(key, (String) value));
                    } else if (value instanceof Integer || value instanceof Long) {
                        // 如果是整数类型
                        params.add(new BasicNameValuePair(key, value.toString()));
                    } else if (value instanceof Float || value instanceof Double) {
                        // 如果是浮点数类型
                        params.add(new BasicNameValuePair(key, value.toString()));
                    } else if (value instanceof Boolean) {
                        // 如果是布尔类型
                        params.add(new BasicNameValuePair(key, value.toString()));
                    } else if (value instanceof Map || value instanceof List) {
                        // 如果是 JSON 对象或数组类型，转换为 JSON 字符串
                        String jsonValue = new ObjectMapper().writeValueAsString(value);
                        params.add(new BasicNameValuePair(key, jsonValue));
                    } else {
                        // 其他类型，转换为字符串
                        params.add(new BasicNameValuePair(key, value.toString()));
                    }
                } catch (Exception e) {
                    logger.error("构建表单数据失败: key={}, value={}", key, value, e);
                    return "构建表单数据失败: " + e.getMessage();
                }
            }
            // 将表单数据编码为 application/x-www-form-urlencoded 格式
            String formData = params.stream()
                    .map(p -> p.getName() + "=" + p.getValue())
                    .collect(Collectors.joining("&"));
            httpPost.setEntity(new StringEntity(formData, ContentType.APPLICATION_FORM_URLENCODED));
        }

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * post json数据
     */
    public static String httpJsonPost(String url, Map<String, String> requestHeaders, JSONObject jsonObj) {
        HttpPost httpPost = new HttpPost(url);

        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        try {
            // 创建 StringEntity 并设置 ContentType 为 application/json
            StringEntity strEntity = new StringEntity(jsonObj.toJSONString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(strEntity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                captureResponseHeaders(response);
                if (response.getCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
                } else {
                    HttpEntity entity = response.getEntity();
                    String code = String.valueOf(response.getCode());
                    return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
                }
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 发送 http put 请求，参数以原生字符串进行提交
     */
    public static String httpJsonPut(String url, Map<String, String> requestHeaders, JSONObject jsonObj) {
        HttpPut httpPut = new HttpPut(url);

        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPut.addHeader(entry.getKey(), entry.getValue());
        }

        try {
            // 创建 StringEntity 并设置 ContentType 为 application/json
            StringEntity strEntity = new StringEntity(jsonObj.toJSONString(), ContentType.APPLICATION_JSON);
            httpPut.setEntity(strEntity);

            try (CloseableHttpResponse response = httpClient.execute(httpPut)) {
                captureResponseHeaders(response);
                if (response.getCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
                } else {
                    HttpEntity entity = response.getEntity();
                    String code = String.valueOf(response.getCode());
                    return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
                }
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 发送 multipart/form-data 类型的 POST 请求，支持文件上传
     *
     * @param url            请求URL
     * @param requestHeaders 请求头
     * @param formData       表单数据，包含普通字段和文件字段
     * @return 响应结果
     */
    public static String httpMultipartPost(String url, Map<String, String> requestHeaders, Map<String, Object> formData) {
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        // 构建 multipart/form-data 请求体
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (Map.Entry<String, Object> entry : formData.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            try {
                if (value instanceof File) {
                    // 如果是文件类型
                    File file = (File) value;
                    builder.addPart(key, new FileBody(file, ContentType.DEFAULT_BINARY));
                } else if (value instanceof String) {
                    // 如果是字符串类型
                    builder.addPart(key, new StringBody((String) value, ContentType.TEXT_PLAIN));
                } else if (value instanceof Integer || value instanceof Long) {
                    // 如果是整数类型
                    builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                } else if (value instanceof Float || value instanceof Double) {
                    // 如果是浮点数类型
                    builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                } else if (value instanceof Boolean) {
                    // 如果是布尔类型
                    builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                } else if (value instanceof Map) {
                    // 如果是 JSON 对象类型
                    String jsonValue = new ObjectMapper().writeValueAsString(value);
                    builder.addPart(key, new StringBody(jsonValue, ContentType.APPLICATION_JSON));
                } else if (value instanceof List) {
                    // 如果是 JSON 数组类型
                    String jsonValue = new ObjectMapper().writeValueAsString(value);
                    builder.addPart(key, new StringBody(jsonValue, ContentType.APPLICATION_JSON));
                } else {
                    // 未知类型，转换为字符串
                    builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                }

            }catch (Exception e) {
                logger.error("构建 multipart/form-data 请求体失败: key={}, value={}", key, value, e);
                return "请求异常:构建请求体失败: " + e.getMessage();
            }
        }

        // 设置请求体
        HttpEntity multipartEntity = builder.build();
        httpPost.setEntity(multipartEntity);

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    public static String httpRawPost(String url, Map<String, String> requestHeaders, String rawData) {
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        if (requestHeaders != null) {
            for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 设置请求体
        StringEntity stringEntity = new StringEntity(rawData, ContentType.TEXT_PLAIN);
        httpPost.setEntity(stringEntity);

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, "UTF-8");
            } else {
                return "请求成功，但响应体为空";
            }
        } catch (Exception e) {
            return "请求异常: " + e.getMessage();
        }
    }
    public static String httpXmlPost(String url, Map<String, String> requestHeaders, String rawData) {
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        if (requestHeaders != null) {
            for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 设置请求体
        StringEntity stringEntity = new StringEntity(rawData, ContentType.APPLICATION_XML);
        httpPost.setEntity(stringEntity);

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, "UTF-8");
            } else {
                return "请求成功，但响应体为空";
            }
        } catch (Exception e) {
            return "请求异常: " + e.getMessage();
        }
    }
    public static String httpHtmlPost(String url, Map<String, String> requestHeaders, String rawData) {
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        if (requestHeaders != null) {
            for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 设置请求体
        StringEntity stringEntity = new StringEntity(rawData, ContentType.TEXT_HTML);
        httpPost.setEntity(stringEntity);

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, "UTF-8");
            } else {
                return "请求成功，但响应体为空";
            }
        } catch (Exception e) {
            return "请求异常: " + e.getMessage();
        }
    }

    /**
     * 发送 DELETE 请求
     *
     * @param url            请求URL
     * @param requestHeaders 请求头
     * @return 响应结果
     */
    public static String httpDelete(String url, Map<String, String> requestHeaders) {
        HttpDelete httpDelete = new HttpDelete(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpDelete.addHeader(entry.getKey(), entry.getValue());
        }

        try (CloseableHttpResponse response = httpClient.execute(httpDelete)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 发送 HEAD 请求
     *
     * @param url            请求URL
     * @param requestHeaders 请求头
     * @return 响应头信息
     */
    public static String httpHead(String url, Map<String, String> requestHeaders) {
        HttpHead httpHead = new HttpHead(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpHead.addHeader(entry.getKey(), entry.getValue());
        }

        try (CloseableHttpResponse response = httpClient.execute(httpHead)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                return "请求成功，响应头为: " + responseHeaders;
            } else {
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::响应头为: " + responseHeaders;
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }


    /**
     * 发送 PATCH 请求
     *
     * @param url            请求URL
     * @param requestHeaders 请求头
     * @param jsonObj        JSON 请求体
     * @return 响应结果
     */
    public static String httpPatch(String url, Map<String, String> requestHeaders, JSONObject jsonObj) {
        HttpPatch httpPatch = new HttpPatch(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPatch.addHeader(entry.getKey(), entry.getValue());
        }

        try {
            // 创建 StringEntity 并设置 ContentType 为 application/json
            StringEntity strEntity = new StringEntity(jsonObj.toJSONString(), ContentType.APPLICATION_JSON);
            httpPatch.setEntity(strEntity);

            try (CloseableHttpResponse response = httpClient.execute(httpPatch)) {
                captureResponseHeaders(response);
                if (response.getCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
                } else {
                    HttpEntity entity = response.getEntity();
                    String code = String.valueOf(response.getCode());
                    return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
                }
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 发送 OPTIONS 请求
     *
     * @param url            请求URL
     * @param requestHeaders 请求头
     * @return 响应头信息
     */
    public static String httpOptions(String url, Map<String, String> requestHeaders) {
        HttpOptions httpOptions = new HttpOptions(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpOptions.addHeader(entry.getKey(), entry.getValue());
        }

        try (CloseableHttpResponse response = httpClient.execute(httpOptions)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                return "请求成功，响应头为: " + responseHeaders;
            } else {
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::响应头为: " + responseHeaders;
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }


    /**
     * 捕获响应头信息
     */
    private static void captureResponseHeaders(CloseableHttpResponse response) {
        if (response != null) {
            Map<String, String> headers = new HashMap<>();
            for (org.apache.hc.core5.http.Header header : response.getHeaders()) {
                headers.put(header.getName(), header.getValue());
            }
            setResponseHeaders(headers);
            logger.info("响应头为：" + headers);
        }
    }


    /**
     * --------------------------
     * 下面是+代理的封装类
     * -------------------------
     */

    /**
     * 使用带代理的 HttpClient 发送 GET 请求
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpCommonGetWithProxy(String url, Map<String, String> requestHeaders, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpGet httpGet = new HttpGet(url);
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpGet.addHeader(entry.getKey(), entry.getValue());
        }

        try (CloseableHttpResponse response = proxyHttpClient.execute(httpGet)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送 POST 请求
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param requestParams  请求参数
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpCommonPostWithProxy(String url, Map<String, String> requestHeaders,
                                                 Map<String, Object> requestParams, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpPost httpPost = new HttpPost(url);
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        if (requestParams != null) {
            List<NameValuePair> params = new ArrayList<>();
            for (Map.Entry<String, Object> entry : requestParams.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            httpPost.setEntity(new StringEntity(params.stream()
                    .map(p -> p.getName() + "=" + p.getValue())
                    .collect(Collectors.joining("&")), ContentType.APPLICATION_FORM_URLENCODED));
        }

        try (CloseableHttpResponse response = proxyHttpClient.execute(httpPost)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送 POST 请求（JSON 数据）
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param jsonObj       JSON 请求体
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpJsonPostWithProxy(String url, Map<String, String> requestHeaders,
                                               JSONObject jsonObj, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpPost httpPost = new HttpPost(url);
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        try {
            // 创建 StringEntity 并设置 ContentType 为 application/json
            StringEntity strEntity = new StringEntity(jsonObj.toJSONString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(strEntity);

            try (CloseableHttpResponse response = proxyHttpClient.execute(httpPost)) {
                captureResponseHeaders(response);
                if (response.getCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
                } else {
                    HttpEntity entity = response.getEntity();
                    String code = String.valueOf(response.getCode());
                    return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
                }
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送 PUT 请求（JSON 数据）
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param jsonObj       JSON 请求体
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpJsonPutWithProxy(String url, Map<String, String> requestHeaders,
                                              JSONObject jsonObj, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpPut httpPut = new HttpPut(url);
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPut.addHeader(entry.getKey(), entry.getValue());
        }

        try {
            // 创建 StringEntity 并设置 ContentType 为 application/json
            StringEntity strEntity = new StringEntity(jsonObj.toJSONString(), ContentType.APPLICATION_JSON);
            httpPut.setEntity(strEntity);

            try (CloseableHttpResponse response = proxyHttpClient.execute(httpPut)) {
                captureResponseHeaders(response);
                if (response.getCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
                } else {
                    HttpEntity entity = response.getEntity();
                    String code = String.valueOf(response.getCode());
                    return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
                }
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送 DELETE 请求
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpDeleteWithProxy(String url, Map<String, String> requestHeaders,
                                             String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpDelete httpDelete = new HttpDelete(url);
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpDelete.addHeader(entry.getKey(), entry.getValue());
        }

        try (CloseableHttpResponse response = proxyHttpClient.execute(httpDelete)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送 PATCH 请求（JSON 数据）
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param jsonObj       JSON 请求体
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpPatchWithProxy(String url, Map<String, String> requestHeaders,
                                            JSONObject jsonObj, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpPatch httpPatch = new HttpPatch(url);
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPatch.addHeader(entry.getKey(), entry.getValue());
        }

        try {
            // 创建 StringEntity 并设置 ContentType 为 application/json
            StringEntity strEntity = new StringEntity(jsonObj.toJSONString(), ContentType.APPLICATION_JSON);
            httpPatch.setEntity(strEntity);

            try (CloseableHttpResponse response = proxyHttpClient.execute(httpPatch)) {
                captureResponseHeaders(response);
                if (response.getCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
                } else {
                    HttpEntity entity = response.getEntity();
                    String code = String.valueOf(response.getCode());
                    return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
                }
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送 multipart/form-data 类型的 POST 请求
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param formData       表单数据（包含普通字段和文件字段）
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpMultipartPostWithProxy(String url, Map<String, String> requestHeaders,
                                                    Map<String, Object> formData, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        // 构建 multipart/form-data 请求体
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (Map.Entry<String, Object> entry : formData.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            try {
                if (value instanceof File) {
                    // 文件类型
                    File file = (File) value;
                    builder.addPart(key, new FileBody(file, ContentType.DEFAULT_BINARY));
                } else if (value instanceof String) {
                    // 字符串类型
                    builder.addPart(key, new StringBody((String) value, ContentType.TEXT_PLAIN));
                } else if (value instanceof Integer || value instanceof Long) {
                    // 整数类型
                    builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                } else if (value instanceof Float || value instanceof Double) {
                    // 浮点数类型
                    builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                } else if (value instanceof Boolean) {
                    // 布尔类型
                    builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                } else if (value instanceof Map || value instanceof List) {
                    // JSON 对象或数组类型
                    String jsonValue = new ObjectMapper().writeValueAsString(value);
                    builder.addPart(key, new StringBody(jsonValue, ContentType.APPLICATION_JSON));
                } else {
                    // 其他类型，转换为字符串
                    builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                }
            } catch (Exception e) {
                logger.error("构建 multipart/form-data 请求体失败: key={}, value={}", key, value, e);
                return "请求异常: 构建请求体失败: " + e.getMessage();
            }
        }

        // 设置请求体
        HttpEntity multipartEntity = builder.build();
        httpPost.setEntity(multipartEntity);

        try (CloseableHttpResponse response = proxyHttpClient.execute(httpPost)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送原始数据 POST 请求
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param rawData       原始数据
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpRawPostWithProxy(String url, Map<String, String> requestHeaders,
                                              String rawData, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        // 设置请求体
        StringEntity stringEntity = new StringEntity(rawData, ContentType.TEXT_PLAIN);
        httpPost.setEntity(stringEntity);

        try (CloseableHttpResponse response = proxyHttpClient.execute(httpPost)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送 HTML 数据 POST 请求
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param htmlData      HTML 数据
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpHtmlPostWithProxy(String url, Map<String, String> requestHeaders,
                                               String htmlData, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        // 设置请求体
        StringEntity stringEntity = new StringEntity(htmlData, ContentType.TEXT_HTML);
        httpPost.setEntity(stringEntity);

        try (CloseableHttpResponse response = proxyHttpClient.execute(httpPost)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }


    /**
     * 使用带代理的 HttpClient 发送 XML 数据 POST 请求
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param xmlData       XML 数据
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应结果
     */
    public static String httpXmlPostWithProxy(String url, Map<String, String> requestHeaders,
                                              String xmlData, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        // 设置请求体
        StringEntity stringEntity = new StringEntity(xmlData, ContentType.APPLICATION_XML);
        httpPost.setEntity(stringEntity);

        try (CloseableHttpResponse response = proxyHttpClient.execute(httpPost)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "UTF-8") : "";
            } else {
                HttpEntity entity = response.getEntity();
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::" + (entity != null ? EntityUtils.toString(entity, "UTF-8") : "");
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送 HEAD 请求
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应头信息
     */
    public static String httpHeadWithProxy(String url, Map<String, String> requestHeaders, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpHead httpHead = new HttpHead(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpHead.addHeader(entry.getKey(), entry.getValue());
        }

        try (CloseableHttpResponse response = proxyHttpClient.execute(httpHead)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                return "请求成功，响应头为: " + responseHeaders;
            } else {
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::响应头为: " + responseHeaders;
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }

    /**
     * 使用带代理的 HttpClient 发送 OPTIONS 请求
     *
     * @param url           请求URL
     * @param requestHeaders 请求头
     * @param proxyHost     代理主机
     * @param proxyPort     代理端口
     * @return 响应头信息
     */
    public static String httpOptionsWithProxy(String url, Map<String, String> requestHeaders, String proxyHost, int proxyPort) {
        // 创建带代理的 HttpClient
        HttpClientWithProxy httpClientWithProxy = new HttpClientWithProxy(proxyHost, proxyPort);
        CloseableHttpClient proxyHttpClient = httpClientWithProxy.getHttpClient();

        HttpOptions httpOptions = new HttpOptions(url);

        // 设置请求头
        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            httpOptions.addHeader(entry.getKey(), entry.getValue());
        }

        try (CloseableHttpResponse response = proxyHttpClient.execute(httpOptions)) {
            captureResponseHeaders(response);
            if (response.getCode() == 200) {
                return "请求成功，响应头为: " + responseHeaders;
            } else {
                String code = String.valueOf(response.getCode());
                return "请求失败:::" + code + ":::响应头为: " + responseHeaders;
            }
        } catch (Exception e) {
            return "请求异常:" + e.getMessage();
        }
    }




}